<template>
  <el-dialog
    :title="!dataForm.featuredId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="55%"
    top="8vh"
  >
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-width="100px" @keyup.enter.native="dataFormSubmit()">
      <el-form-item label="推荐位名称" prop="featuredName">
        <el-input v-model="dataForm.featuredName" placeholder="推荐位名称" />
      </el-form-item>
      <el-form-item label="推荐位图片" prop="featuredImage">
        <el-upload
          ref="my-upload"
          class="upload-demo"
          action="http://localhost:8765/admin/oss/file/upload?module=featured"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          :on-exceed="handleUploadExceed"
          :before-upload="beforeAvatarUpload"
          :file-list="fileList"
          list-type="picture"
          :limit="1"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2Mb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="推荐位链接" prop="featuredLink">
        <el-input v-model="dataForm.featuredLink" placeholder="推荐位链接" />
      </el-form-item>
      <el-form-item label="推荐位风格" prop="featuredColor">
        <el-color-picker v-model="dataForm.featuredColor" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>

import rqApi from '@/api/featured'

export default {
  data() {
    return {
      visible: false,
      dataForm: {
        featuredId: '',
        featuredName: '',
        featuredImage: '',
        featuredLink: '',
        featuredColor: '',
        creationTime: '',
        modificationTime: ''
      },
      dataRule: {
        featuredName: [
          { required: true, message: '推荐位名称不能为空', trigger: 'blur' }
        ],
        featuredImage: [
          { required: true, message: '推荐位图片不能为空', trigger: 'blur' }
        ],
        featuredLink: [
          { required: true, message: '推荐位链接不能为空', trigger: 'blur' }
        ],
        featuredColor: [
          { required: true, message: '推荐位风格不能为空', trigger: 'blur' }
        ]
      },
      fileList: []
    }
  },
  methods: {
    init(id) {
      this.dataForm.featuredId = id || ''
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.featuredId) {
          rqApi.getInfo(this.dataForm.featuredId).then(({ data }) => {
            if (data) {
              this.dataForm.featuredName = data.featuredIrst.featuredName
              this.fileList = [{ 'url': data.featuredIrst.featuredImage }]
              this.dataForm.featuredImage = data.featuredIrst.featuredImage
              this.dataForm.featuredLink = data.featuredIrst.featuredLink
              this.dataForm.featuredColor = data.featuredIrst.featuredColor
              this.dataForm.creationTime = data.featuredIrst.creationTime
              this.dataForm.modificationTime = data.featuredIrst.modificationTime
            }
          })
        } else {
          this.fileList = []
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.dataForm.featuredId) {
            rqApi.save(this.dataForm).then(({ data }) => {
              if (data) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                    this.$refs['my-upload'].clearFiles()
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          } else {
            rqApi.update(this.dataForm).then(({ data }) => {
              if (data) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                    this.$refs['my-upload'].clearFiles()
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        }
      })
    },
    // 上传多于一个文件
    handleUploadExceed(files, fileList) {
      this.$message.warning('想要重新上传图片，请先删除已上传的视频')
    },
    // 上传校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 上传成功回调
    handleAvatarSuccess(res, file) {
      console.log(res)
      if (res.success) {
        // console.log(res)
        this.dataForm.featuredImage = res.data.url
        // 强制重新渲染
        // this.$forceUpdate()
      } else {
        this.$message.error('上传失败1')
      }
    },

    // 错误处理
    handleAvatarError() {
      this.$message.error('上传失败2')
    }
  }
}
</script>
